package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.Nonce;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * User: Viktor
 * Date: 12/3/13
 */
public class NonceDAO extends DAO<Nonce>
{
	@Override
	public void create(Nonce o)
	{
		String sql = "INSERT INTO NONCES(NONCE, EXPIRES) VALUES (?, ?)";
		jdbcTemplate.update(sql, o.getNonce(), o.getExpires());
	}

	@Override
	public void update(Nonce o)
	{

	}

	public Nonce getByNonce(String nonce)
	{
		List<Nonce> list;
		String sql = "SELECT * FROM NONCES WHERE NONCE = ?";
		list = jdbcTemplate.query(sql, new NonceRowMapper(), nonce);
		return list.isEmpty()?null:list.get(0);

	}


	@Override
	public Nonce getById(int id)
	{
		return null;
	}

	@Override
	public Collection<Nonce> getAll()
	{
		return null;
	}

	@Override
	public void deleteById(int id)
	{

	}
	private static final class NonceRowMapper implements ParameterizedRowMapper<Nonce>
	{
		public Nonce mapRow(ResultSet rs, int rowNum) throws SQLException
		{
			Nonce nonce= new Nonce();
			nonce.setNonce(rs.getString("nonce"));
			nonce.setExpires(rs.getLong("expires"));
			return nonce;
		}
	}
}
